package com.hcbd.tdwt.ui.xingyu.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.BdManager;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.github.mikephil.charting.charts.BarChart;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.base.BaseFragment;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.GlobalParams;
import com.hcbd.tdwt.ui.xingyu.dialog.OldProtocolDialog;
import com.hcbd.tdwt.ui.xingyu.service.KeepLifeService;
import com.hcbd.tdwt.ui.xingyu.vo.MenuIconVO_Table;
import com.hcbd.tdwt.util.ChartUtil;
import com.pangu.bdsdk2021.bluetooth.BluetoothManage;
import com.pangu.bdsdk2021.entity.terminalone.BDICInfo;
import com.pangu.bdsdk2021.entity.terminalone.BDTXInfo;
import com.pangu.bdsdk2021.entity.terminalthree.BDSXXInfo;
import com.pangu.bdsdk2021.entity.terminalthree.BDSnrInfo;
import com.hcbd.tdwt.base.bd.XYSerialPortManage;
import com.hcbd.tdwt.ui.xingyu.activity.AddContactActivity_;
import com.hcbd.tdwt.ui.xingyu.activity.AddressBookActivity_;
import com.hcbd.tdwt.ui.xingyu.activity.BdPositionActivity_;
import com.hcbd.tdwt.ui.xingyu.activity.BdStatusActivity_;
import com.hcbd.tdwt.ui.xingyu.activity.LocationUploadActivity_;
import com.hcbd.tdwt.ui.xingyu.activity.MenuSettingActivity_;
import com.hcbd.tdwt.ui.xingyu.activity.ReportPeaceActivity_;
import com.hcbd.tdwt.ui.xingyu.activity.SendMessageActivity_;
import com.hcbd.tdwt.ui.xingyu.adapter.ContactMsgAdapter;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact_Table;
import com.hcbd.tdwt.ui.xingyu.vo.MenuIconVO;

import com.pangu.bdsdk2021.entity.terminalthreeofficial.BdTciInfo;
import com.pangu.bdsdk2021.terminal.listener.TerminalListener2_1;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO_Table;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.Touch;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static android.content.Context.SENSOR_SERVICE;

/**
 *  create zzh
 *  星宇主页fragment
 */
@RequiresApi(api = 31)
@SuppressLint("NonConstantResourceId")
@EFragment(R.layout.fragment_home_xingyu)
public class HomeFragment extends BaseFragment implements SensorEventListener{
    @ViewById(R.id.compass)
    ImageView compass;
    @ViewById(R.id.direction_tv)
    TextView direction;
    @ViewById(R.id.mBarChart)
    BarChart mBarChart;
    @ViewById(R.id.not_connected_ll)
    LinearLayout  notConnectedLL;
    @ViewById(R.id.connected_ll)
    LinearLayout connectedLL;
    @ViewById(R.id.card_number_tv)
    TextView cardNumber;
    @ViewById(R.id.disconnect_btn)
    Button disconnectBtn;
    @ViewById(R.id.connected_btn)
    Button connectedBtn;
    @ViewById
    TextView bluetoothName,electricityTv,cardLevelTv,serviceFrequency;
    @ViewById
    ImageView signalHide,signalShow;
    @ViewById
    LinearLayout barParentLL;
    @ViewById
    LinearLayout oneLL,twoLL,threeLL,fourLL;
    @ViewById
    LinearLayout fivesLL,sixLL,sevenLL,menuSettingLL,bluetoothNameLL,electricityLL;
    @ViewById
    ImageView menuSettingImg;
    @ViewById
    RecyclerView contactRV;
    @ViewById
    TextView connected_tip_tv;
    @ViewById
    View electricityView,bluetoothNameView;
    private List<BoxContact>contactList;
    private SensorManager sManager;
    private Sensor mSensorOrientation;
    private int currentDegree;
    private Drawable onMsgDb,sendMsgDb;
    private Drawable onContactDb,contactDb;
    private Drawable onBdEquipmentDb,bdEquipmentDb;
    private Drawable onCommandCenterDb,commandCenterDb;
    private Drawable onOkDb,okDb;
    private Drawable onLocationUploadDb,locationUploadDb;
    private Drawable onBdLocationDb,bdLocationDb;
    private Drawable onMenuSettingDb,menuSettingDb;
    private LayoutInflater mInflater;
    private ContactMsgAdapter contactMsgAdapter;

    final private int refresh_code=5;
    private ChartUtil chartUtil;
    public String shutDownTip="是否断开蓝牙连接？";
    @AfterViews
    protected void init() {
        initMsgRegister();
        contactList=new ArrayList<>();
        sManager = (SensorManager) this.getActivity().getSystemService(SENSOR_SERVICE);
        mInflater = this.getActivity().getLayoutInflater();
        mSensorOrientation = sManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);

        chartUtil=new ChartUtil(this.getContext(),mBarChart);
        chartUtil.setBottomColor(R.color.bright_green);
        chartUtil.setTopColor(R.color.light_green);
        chartUtil.setLeftTextColor(R.color.white);
        chartUtil.setxGridColor(R.color.dark_green);
        chartUtil.setxTvColor(R.color.white);
        chartUtil.initChart();
        initIcon();
        initMenu();
        initContactData();
        if(BdToolFactory.MOBILE_PHONE_TYPE==BdToolFactory.SATELLITE_MOBILE_PHONE){
            connected_tip_tv.setText("未打开北斗服务");
            connectedBtn.setText("打开北斗服务");
            bluetoothNameLL.setVisibility(View.GONE);
            electricityLL.setVisibility(View.GONE);
            electricityView.setVisibility(View.GONE);
            bluetoothNameView.setVisibility(View.GONE);
            shutDownTip="是否关闭北斗服务？";
        }
        refreshStatus();

    }



    //联系人列表初始化
    public void initContactData(){
        contactList= SQLite.select().from(BoxContact.class).orderBy(BoxContact_Table.recentCommunicationTime, false).queryList();
        if(contactMsgAdapter==null){
            contactMsgAdapter=new ContactMsgAdapter(this.getContext(),contactList);
            contactMsgAdapter.setHasStableIds(true);
        }else{
            contactMsgAdapter.notifyDataSetChanged(contactList);
            return;
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this.getContext(), 1);
        contactRV.setLayoutManager(gridLayoutManager);
        contactRV.setAdapter(contactMsgAdapter);
        contactMsgAdapter.setOnItemClickListener(new ContactMsgAdapter.OnItemClickListener() {
            @Override
            public void onClick(BoxContact boxContact,View view) {
                Intent intent=new Intent();
                intent.setClass(getContext(), SendMessageActivity_.class);
                if(GlobalParams.commandCentreNumber.equals(boxContact.getBoxId())){
                    intent.putExtra("receiverNumber",GlobalParams.commandCentreNumber);
                    intent.putExtra("entryMode",Constant.ENTRY_SEND_CENTER_NUMBER);
                }else{
                    intent.putExtra("receiverNumber",boxContact.getBoxId());
                    intent.putExtra("entryMode",Constant.ENTRY_SEND_USER_MSG);
                }
                intent.putExtra("receiverName",boxContact.getName());
                startActivityForResult(intent,refresh_code);
            }

            @Override
            public void onEdit(BoxContact boxContact) {
                Intent intent=new Intent();
                intent.setClass(getContext(), AddContactActivity_.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("boxContact",boxContact);
                intent.putExtras(bundle);
                intent.putExtra("entryMode",1);
                startActivityForResult(intent,refresh_code);
            }

            @Override
            public void onDel(BoxContact boxContact) {
                try {
                    boxContact.delete();
                    SQLite.delete(UserMessageVO.class)
                            .where(UserMessageVO_Table.receiverNumber.eq(boxContact.getBoxId()))
                            .execute();
                    Constant.msgPageIsRefresh=true;
                }catch (Exception e){
                    e.printStackTrace();
                }
                initContactData();
            }
        });
    }
    //菜单初始化
    @SuppressLint("ClickableViewAccessibility")
    public void initMenu(){
        oneLL.removeAllViews();
        twoLL.removeAllViews();
        threeLL.removeAllViews();
        fourLL.removeAllViews();
        fivesLL.removeAllViews();
        sixLL.removeAllViews();
        sevenLL.removeAllViews();
        List<MenuIconVO> list= SQLite.select().from(MenuIconVO.class).queryList();
        for(int i=0;i<list.size();i++){
            MenuIconVO menuIconVO=list.get(i);
            if(menuIconVO.isShow==0){
                continue;
            }
            View view=mInflater.inflate(R.layout.home_icon_item,null, false);
            ImageView imageView=view.findViewById(R.id.menuImg);
            TextView menuName=view.findViewById(R.id.menuName);
            menuName.setText(menuIconVO.menuName);
            LinearLayout linearLayout=null;
            if(menuIconVO.index==1){
                oneLL.addView(view);
                linearLayout=oneLL;
            }else if(menuIconVO.index==2){
                twoLL.addView(view);
                linearLayout=twoLL;
            }else if(menuIconVO.index==3){
                threeLL.addView(view);
                linearLayout=threeLL;
            }else if(menuIconVO.index==4){
                fourLL.addView(view);
                linearLayout=fourLL;
            }else if(menuIconVO.index==5){
                fivesLL.addView(view);
                linearLayout=fivesLL;
            }else if(menuIconVO.index==6){
                sixLL.addView(view);
                linearLayout=sixLL;
            }else if(menuIconVO.index==7){
                sevenLL.addView(view);
                linearLayout=sevenLL;
            }
            if(linearLayout==null){
                continue;
            }
            setTouch(menuIconVO.iconType,linearLayout,imageView);
        }
    }
    //点击效果
    @SuppressLint("ClickableViewAccessibility")
    public void setTouch(String type, LinearLayout linearLayout, ImageView imageView){
        if("messageImg".equals(type)){
            imageView.setBackground(sendMsgDb);
            linearLayout.setOnTouchListener((view1, motionEvent) -> {
                if(onPreImg(motionEvent,imageView,sendMsgDb,onMsgDb)){
                    Intent intent=new Intent();
                    intent.setClass(Objects.requireNonNull(getContext()), SendMessageActivity_.class);
                    startActivityForResult(intent,refresh_code);
                }
                return true;
            });
        }else  if("contactImg".equals(type)){
            imageView.setBackground(contactDb);
            linearLayout.setOnTouchListener((view1, motionEvent) -> {
                if(onPreImg(motionEvent,imageView,contactDb,onContactDb)){
                    Intent intent=new Intent();
                    intent.setClass(Objects.requireNonNull(getContext()), AddressBookActivity_.class);
                    intent.putExtra("entryMode",2);
                    startActivityForResult(intent,ADD_CONTACT_CODE);
               /*   String str="$BDTCI,254991,254991,1,000000,2,0,91000000000064E3494C00000000000000000000CED2D2D1BEADB0B2C8ABB5BDB4EFC4BFB5C4B5D8";
                    BdManager.getInstance().onBdTciInfo(build2_1(str));*/
                }
                return true;
            });
        }else  if("bdEquipmentImg".equals(type)){
            imageView.setBackground(bdEquipmentDb);
            linearLayout.setOnTouchListener((view1, motionEvent) -> {
                if(onPreImg(motionEvent,imageView,bdEquipmentDb,onBdEquipmentDb)){
                 /*   if(!BeidouBoxParams.isBoxConnectNormal){
                        toast("请连接北斗盒子！");
                    }else {*/
                    Intent intent = new Intent();
                    intent.setClass(getContext(), BdStatusActivity_.class);
                    startActivity(intent);
                    /* }*/
                }
                return true;
            });
        }else  if("commandCenterImg".equals(type)){
            imageView.setBackground(commandCenterDb);
            linearLayout.setOnTouchListener((view1, motionEvent) -> {
                if(onPreImg(motionEvent,imageView,commandCenterDb,onCommandCenterDb)){
                    Intent intent=new Intent();
                    intent.setClass(getContext(), SendMessageActivity_.class);
                    intent.putExtra("receiverNumber",GlobalParams.commandCentreNumber);
                    intent.putExtra("receiverName","指挥中心");
                    intent.putExtra("entryMode",Constant.ENTRY_SEND_CENTER_NUMBER);
                    startActivityForResult(intent,refresh_code);
                }
                return true;
            });
        }else  if("okImg".equals(type)){
            imageView.setBackground(okDb);
            linearLayout.setOnTouchListener((view1, motionEvent) -> {
                if(onPreImg(motionEvent,imageView,okDb,onOkDb)){
                    Intent intent=new Intent();
                    intent.setClass(getContext(), ReportPeaceActivity_.class);
                    startActivity(intent);
                }
                return true;
            });
        }else  if("locationUploadImg".equals(type)){
            imageView.setBackground(locationUploadDb);
            linearLayout.setOnTouchListener((view1, motionEvent) -> {
                if(onPreImg(motionEvent,imageView,locationUploadDb,onLocationUploadDb)){
                    Intent intent=new Intent();
                    intent.setClass(getContext(), LocationUploadActivity_.class);
                    startActivity(intent);
                }
                return true;
            });
        }else  if("bdLocationImg".equals(type)){
            imageView.setBackground(bdLocationDb);
            linearLayout.setOnTouchListener((view1, motionEvent) -> {
                if(onPreImg(motionEvent,imageView,bdLocationDb,onBdLocationDb)){
                    Intent intent=new Intent();
                    intent.setClass(getContext(), BdPositionActivity_.class);
                    startActivity(intent);
                }
                return true;
            });
        }
    }
    public BdTciInfo build2_1(String str) {
        BdTciInfo bdTciInfo=new BdTciInfo();
        String[] items = str.split(",");
        if (items.length > 6) {
            bdTciInfo.setTransmittingTheID(items[1]);
            bdTciInfo.setTheReceivingPartyID(items[2]);
            bdTciInfo.setFrequencyPoint(items[3]);
            bdTciInfo.setTime(items[4]);
            bdTciInfo.setCodingCategories(items[5]);
            bdTciInfo.setMsgType(items[5]);
            bdTciInfo.setSDID(items[6]);
            bdTciInfo.setMsgContent(items[7]);
        } else {
            bdTciInfo.setTransmittingTheID("00");
            bdTciInfo.setTheReceivingPartyID("00");
            bdTciInfo.setFrequencyPoint("00");
            bdTciInfo.setTime("00");
            bdTciInfo.setCodingCategories("00");
            bdTciInfo.setSDID("00");
            bdTciInfo.setCommunicationData("00");
        }
        return  bdTciInfo;
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void eventBus(UserMessageVO userMessage){
        initContactData();
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(BDSnrInfo bdSnrInfo){
        chartUtil.updateChartData();
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(BDICInfo bdicInfo){
        refreshStatus();
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(BDSXXInfo bdsxxInfo){
        refreshStatus();
        MainApp.getInstance().hideLoading();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(String bleContent){
        refreshStatus();
    }
    //指针移动
    public void roteCompass(int degree){
        if (degree == 0||currentDegree==degree) {
            return;
        }
        RotateAnimation ra = new RotateAnimation(currentDegree,degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        ra.setInterpolator(new LinearInterpolator());
        ra.setDuration(200);//动画时间200毫秒
        ra.setFillAfter(true);//设置动画结束后的保留状态
        compass.startAnimation(ra);
        currentDegree = degree;
    }
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if(sensorEvent.sensor.getType()==Sensor.TYPE_ORIENTATION){
            roteCompass((int) sensorEvent.values[0]);
        }
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    //断开连接
    @Click
    void disconnectBtn(){
        showOldProtocolDialog(shutDownTip, (dialog, confirm) -> {
            if (confirm) {
                BdToolFactory.getBdSendBase().close(getActivity());
            }
            dialog.dismiss();
        });
    }
    @Click
    void connectedBtn(){
        BdToolFactory.getBdSendBase().open(getActivity(),BLUETOOTH_CONNECT_CODE);
    }
    private final int BLUETOOTH_CONNECT_CODE=1;//蓝牙连接返回
    private final int ADD_CONTACT_CODE=5;//添加联系人返回
    private final int MENU_RESULT=6;//菜单保存返回！
    @OnActivityResult(ADD_CONTACT_CODE)
    public void resultContact(int resultCode){
        if(resultCode==Activity.RESULT_OK){
            initContactData();
            Constant.msgPageIsRefresh=true;
        }
    }
    @OnActivityResult(MENU_RESULT)
    public void resultMenuResult(int resultCode){
        if(resultCode==Activity.RESULT_OK){
            initMenu();
        }
    }
    @OnActivityResult(refresh_code)
    public void resultMsgList(int resultCode){
        if(resultCode== Activity.RESULT_OK){
            initContactData();
            Constant.msgPageIsRefresh=true;
        }
    }
    @Click//信号隐藏
    void signalHide(){
        signalHide.setVisibility(View.GONE);
        signalShow.setVisibility(View.VISIBLE);
        barParentLL.setVisibility(View.VISIBLE);
    }
    @Click//信号显示
    void signalShow(){
        signalShow.setVisibility(View.GONE);
        signalHide.setVisibility(View.VISIBLE);
        barParentLL.setVisibility(View.GONE);
    }



    @Touch
    void menuSettingLL(MotionEvent event){
        if(onPreImg(event,menuSettingImg,menuSettingDb,onMenuSettingDb)){
            Intent intent=new Intent();
            intent.setClass(getContext(), MenuSettingActivity_.class);
            startActivityForResult(intent,MENU_RESULT);
        }
    }


    public boolean onPreImg(MotionEvent event,ImageView img,Drawable preDb,Drawable onDb){
        if(event.getAction()==MotionEvent.ACTION_DOWN){
            img.setBackground(onDb);
            return false;
        }else if(event.getAction()==MotionEvent.ACTION_UP){
            img.setBackground(preDb);
            return true;
        }else if(event.getAction()==MotionEvent.ACTION_MOVE){
            img.setBackground(preDb);
            return false;
        }else {
            img.setBackground(preDb);
            return false;
        }
    }




    private void initIcon(){
        onMsgDb=getActivity().getDrawable(R.drawable.on_message);
        sendMsgDb=getActivity().getDrawable(R.drawable.send_message);
        onContactDb=getActivity().getDrawable(R.drawable.on_contact);
        contactDb=getActivity().getDrawable(R.drawable.new_contact);
        onBdEquipmentDb=getActivity().getDrawable(R.drawable.on_bd_equipment);
        bdEquipmentDb=getActivity().getDrawable(R.drawable.bd_equipment);
        onCommandCenterDb=getActivity().getDrawable(R.drawable.on_command_center);
        commandCenterDb=getActivity().getDrawable(R.drawable.command_center);
        onOkDb=getActivity().getDrawable(R.drawable.on_home_ok);
        okDb=getActivity().getDrawable(R.drawable.home_ok);
        onLocationUploadDb=getActivity().getDrawable(R.drawable.on_location_upload);
        locationUploadDb=getActivity().getDrawable(R.drawable.location_upload);
        onBdLocationDb=getActivity().getDrawable(R.drawable.on_bd_location);
        bdLocationDb=getActivity().getDrawable(R.drawable.bd_location);
        onMenuSettingDb=getActivity().getDrawable(R.drawable.on_menu_setting);
        menuSettingDb=getActivity().getDrawable(R.drawable.menu_setting);
    }

    /**
     * 初始化终端状态
     */
    private void refreshStatus() {

        chartUtil.updateChartData();
        if (!BeidouBoxParams.isBoxConnectNormal) {
            notConnectedLL.setVisibility(View.VISIBLE);
            connectedLL.setVisibility(View.GONE);
            signalShow();
        } else {
            connectedLL.setVisibility(View.VISIBLE);
            notConnectedLL.setVisibility(View.GONE);
            cardNumber.setText(String.format("北斗卡号:%s", BeidouBoxParams.userCardNumber));
            bluetoothName.setText(BeidouBoxParams.blueName);
            electricityTv.setText(MessageFormat.format("{0}%", BeidouBoxParams.kwh));
            cardLevelTv.setText(String.valueOf(BeidouBoxParams.cardType));
            serviceFrequency.setText(MessageFormat.format("{0}秒", BeidouBoxParams.sendFreq));
        }
    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
    @Override
    public void onSwitch() {
        super.onSwitch();
        if(Constant.homePageIsRefresh&&contactMsgAdapter!=null){
            initContactData();
            Constant.homePageIsRefresh=false;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (sManager != null) {
            sManager.unregisterListener(this);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initContactData();
        sManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_UI);
    }
}
